﻿using Common.MefHelp.Attributes;

namespace Common.Self.Computer
{
    /// <summary>
    /// Linux资源实现类
    /// </summary>
    [CustomInjection("linux", typeof(IResource))]
    public class LinuxResource : IResource
    {
        /// <summary>
        /// 获取Cpu资源
        /// </summary>
        /// <returns></returns>
        public Task<float> GetCpuAsync()
        {
            string[] cpuStats = File.ReadAllLines("/proc/stat");
            string cpuLine = cpuStats[0]; // 第一行包含总的 CPU 统计信息
            string[] cpuInfo = cpuLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            int totalCpuTime = 0;
            for (int i = 1; i < cpuInfo.Length; i++)
            {
                totalCpuTime += int.Parse(cpuInfo[i]);
            }

            int idleTime = int.Parse(cpuInfo[4]); // 空闲 CPU 时间
            float cpuUsage = 100.0f * (1.0f - (idleTime / (float)totalCpuTime));
            return Task.FromResult(cpuUsage);
        }
        /// <summary>
        /// 获取可用内存
        /// </summary>
        /// <returns></returns>
        public Task<float> GetAvailableMemeoryAsync()
        {
            string[] memInfo = File.ReadAllLines("/proc/meminfo");
            //string totalMemLine = memInfo[0];
            string freeMemLine = memInfo[1];

            //int totalMemory = int.Parse(totalMemLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1]);
            float freeMemory = float.Parse(freeMemLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1]);

            //float usedMemory = totalMemory - freeMemory;
            //float memoryUsage = (usedMemory / totalMemory) * 100.0f;
            return Task.FromResult(freeMemory);
        }
    }
}
